/* eslint-disable node/prefer-global/process */

import { OpenAI } from 'openai'
import { z } from 'zod'

// Define the schema for layer analysis
const layerSchema = z.object({
  type: z.enum(['text', 'image', 'shape']),
  content: z.string(),
  position: z.object({
    x: z.number(),
    y: z.number(),
    width: z.number(),
    height: z.number(),
  }),
  style: z.object({
    fontSize: z.string().optional(),
    fontFamily: z.string().optional(),
    fontWeight: z.string().optional(),
    fontStyle: z.string().optional(),
    lineHeight: z.string().optional(),
    letterSpacing: z.string().optional(),
    textAlign: z.string().optional(),
    textDecoration: z.string().optional(),
    color: z.string().optional(),
    backgroundColor: z.string().optional(),
    borderColor: z.string().optional(),
    borderWidth: z.string().optional(),
    borderRadius: z.string().optional(),
    boxShadow: z.string().optional(),
    textShadow: z.string().optional(),
    opacity: z.string().optional(),
    padding: z.string().optional(),
    margin: z.string().optional(),
    rotation: z.string().optional(),
  }),
  metadata: z.object({
    confidence: z.number(),
    language: z.string().optional(),
    estimatedFont: z.string().optional(),
    imageType: z.string().optional(),
  }),
})

const analysisSchema = z.object({
  dimensions: z.object({
    width: z.number(),
    height: z.number(),
  }),
  layers: z.array(layerSchema),
})

// --- VLLM/OpenAI configuration ---
const VLLM_API_BASE_URL = process.env.VLLM_API_BASE_URL || 'http://10.112.8.3:8307/v1'
const VLLM_MODEL_NAME = process.env.VLLM_MODEL_NAME || '/data/hpc/home/yue.wang04/models/qvl/Qwen2.5-VL-72B-Instruct'
const API_TIMEOUT_MS = Number(process.env.VLLM_API_TIMEOUT_MS || 180000)
const TEMPERATURE = Number(process.env.VLLM_TEMPERATURE || 0)
const MAX_TOKENS = process.env.VLLM_MAX_TOKENS ? Number(process.env.VLLM_MAX_TOKENS) : 4000

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY || 'sk-no-key-required',
  baseURL: VLLM_API_BASE_URL,
  timeout: API_TIMEOUT_MS,
})

export async function POST(request: Request) {
  try {
    //     console.log('[v0] Starting image analysis')
    //     const { image, modelName, prompt } = await request.json()

    //     if (!image) {
    //       console.log('[v0] No image provided')
    //       return Response.json({ error: 'No image provided' }, { status: 400 })
    //     }

    //     // 使用传入的模型名称，如果没有则使用默认值
    //     const effectiveModel = modelName || VLLM_MODEL_NAME
    //     console.log('[v0] Image received, calling AI model:', effectiveModel)

    //     // 使用传入的 prompt，如果没有则使用默认提示词
    //     const promptText = prompt || `You are an expert image analysis AI. Analyze this image with EXTREME PRECISION and identify ALL distinct visual layers including text, shapes, and images.

    // CRITICAL REQUIREMENTS:
    // 1. Provide EXACT pixel coordinates for position {x, y, width, height}
    // 2. Identify EVERY text element separately (headlines, body text, captions, labels, buttons)
    // 3. Detect ALL shapes (rectangles, circles, lines, icons, backgrounds)
    // 4. Identify ALL image elements (photos, illustrations, logos, icons)

    // For TEXT layers, include:
    // - Exact text content
    // - Precise position and dimensions
    // - Font size, family, weight, style
    // - Color, alignment, line height, letter spacing
    // - Confidence score and language

    // For IMAGE layers, include:
    // - Detailed description of image content
    // - Exact position and dimensions
    // - Border radius, box shadow, opacity, rotation
    // - Confidence score and image type (photo/illustration/icon)

    // For SHAPE layers, include:
    // - Description (rectangle background, circle button, line divider, etc.)
    // - Exact position and dimensions
    // - Background color, border properties, border radius
    // - Box shadow and opacity
    // - Confidence score

    // Order layers from background to foreground. Be as precise as possible with measurements.

    // Output ONLY valid JSON with this exact TypeScript-like schema (no markdown, no extra text):
    // { "layers": [ { "type": "text" | "image" | "shape", "content": string, "position": { "x": number, "y": number, "width": number, "height": number }, "style": { "fontSize"?: string, "fontFamily"?: string, "fontWeight"?: string, "fontStyle"?: string, "lineHeight"?: string, "letterSpacing"?: string, "textAlign"?: string, "textDecoration"?: string, "color"?: string, "backgroundColor"?: string, "borderColor"?: string, "borderWidth"?: string, "borderRadius"?: string, "boxShadow"?: string, "textShadow"?: string, "opacity"?: string, "padding"?: string, "margin"?: string, "rotation"?: string }, "metadata": { "confidence": number, "language"?: string, "estimatedFont"?: string, "imageType"?: string } } ] }`

    //     console.log('[v0] Using prompt length:', promptText.length)

    //     const completion = await openai.chat.completions.create({
    //       model: effectiveModel,
    //       temperature: TEMPERATURE,
    //       max_tokens: MAX_TOKENS,
    //       messages: [
    //         {
    //           role: 'user',
    //           content: [
    //             { type: 'text', text: promptText },
    //             { type: 'image_url', image_url: { url: image } },
    //             { type: 'text', text: 'Return only JSON, no explanation.' },
    //           ],
    //         },
    //       ],
    //     })

    //     const content = completion.choices?.[0]?.message?.content || ''

    //     // Strip optional markdown fences if present
    //     const jsonText = content
    //       .replace(/^```json\s*/i, '')
    //       .replace(/^```\s*/, '')
    //       .replace(/```\s*$/, '')
    //       .trim()

    //     let parsed
    //     try {
    //       parsed = JSON.parse(jsonText)
    //     }
    //     catch {
    //       console.error('[v0] Failed to parse JSON from model:', content)
    //       throw new Error('Model did not return valid JSON')
    //     }

    //     const object = analysisSchema.parse(parsed)

    //     console.log('[v0] AI response received, processing layers')

    //     const layers = object.layers.map((layer, index) => ({
    //       id: `layer-${index}`,
    //       ...layer,
    //     }))

    //     console.log('[v0] Returning', layers.length, 'layers')
    //     return Response.json({ layers })

    // 以下是测试数据，实际使用时请注释掉或删除
    return Response.json({
      layers: [
        {
          id: 'layer-0',
          type: 'shape',
          content: 'Full page background - solid yellow/gold color',
          position: {
            x: 0,
            y: 0,
            width: 1024,
            height: 1024,
          },
          style: {
            backgroundColor: '#F4C542',
            opacity: '1',
          },
          metadata: {
            confidence: 1,
          },
        },
        {
          id: 'layer-1',
          type: 'image',
          content: 'Pulsar logo - circular blue icon with stylized \'P\' symbol inside',
          position: {
            x: 47,
            y: 46,
            width: 52,
            height: 52,
          },
          style: {
            borderRadius: '50%',
            opacity: '1',
          },
          metadata: {
            confidence: 0.95,
            imageType: 'icon',
          },
        },
        {
          id: 'layer-2',
          type: 'text',
          content: 'Pulsar',
          position: {
            x: 108,
            y: 46,
            width: 160,
            height: 52,
          },
          style: {
            fontSize: '48px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'left',
            color: '#1E4D8B',
          },
          metadata: {
            confidence: 0.98,
            language: 'es',
          },
        },
        {
          id: 'layer-3',
          type: 'text',
          content: 'Monto del préstamo',
          position: {
            x: 312,
            y: 148,
            width: 400,
            height: 48,
          },
          style: {
            fontSize: '36px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'center',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-4',
          type: 'text',
          content: 'MXN $20,000',
          position: {
            x: 316,
            y: 208,
            width: 392,
            height: 88,
          },
          style: {
            fontSize: '64px',
            fontFamily: 'sans-serif',
            fontWeight: '800',
            textAlign: 'center',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-5',
          type: 'shape',
          content: 'White rounded rectangle background for pricing table and button',
          position: {
            x: 134,
            y: 350,
            width: 756,
            height: 474,
          },
          style: {
            backgroundColor: '#F5F5F5',
            borderRadius: '32px',
            boxShadow: '0px 8px 16px rgba(0,0,0,0.1)',
          },
          metadata: {
            confidence: 0.97,
          },
        },
        {
          id: 'layer-6',
          type: 'shape',
          content: 'Orange header row background for table',
          position: {
            x: 162,
            y: 388,
            width: 700,
            height: 72,
          },
          style: {
            backgroundColor: '#F4A460',
            borderRadius: '8px',
          },
          metadata: {
            confidence: 0.95,
          },
        },
        {
          id: 'layer-7',
          type: 'text',
          content: 'Monto del préstamo',
          position: {
            x: 174,
            y: 408,
            width: 226,
            height: 32,
          },
          style: {
            fontSize: '20px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'left',
            color: '#000000',
          },
          metadata: {
            confidence: 0.98,
            language: 'es',
          },
        },
        {
          id: 'layer-8',
          type: 'text',
          content: 'plazos de pago',
          position: {
            x: 436,
            y: 408,
            width: 175,
            height: 32,
          },
          style: {
            fontSize: '20px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'center',
            color: '#000000',
          },
          metadata: {
            confidence: 0.98,
            language: 'es',
          },
        },
        {
          id: 'layer-9',
          type: 'text',
          content: 'Pago quincenal',
          position: {
            x: 659,
            y: 408,
            width: 187,
            height: 32,
          },
          style: {
            fontSize: '20px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'left',
            color: '#000000',
          },
          metadata: {
            confidence: 0.98,
            language: 'es',
          },
        },
        {
          id: 'layer-10',
          type: 'shape',
          content: 'White background for first data row',
          position: {
            x: 162,
            y: 472,
            width: 700,
            height: 72,
          },
          style: {
            backgroundColor: '#FFFFFF',
            borderRadius: '0px',
          },
          metadata: {
            confidence: 0.94,
          },
        },
        {
          id: 'layer-11',
          type: 'text',
          content: 'MXN $8,000',
          position: {
            x: 195,
            y: 486,
            width: 167,
            height: 44,
          },
          style: {
            fontSize: '28px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'left',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-12',
          type: 'text',
          content: '6 quincenas',
          position: {
            x: 444,
            y: 486,
            width: 160,
            height: 44,
          },
          style: {
            fontSize: '28px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'center',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-13',
          type: 'text',
          content: 'MXN $1,560',
          position: {
            x: 665,
            y: 486,
            width: 165,
            height: 44,
          },
          style: {
            fontSize: '28px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'left',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-14',
          type: 'shape',
          content: 'Green background for second data row (selected/highlighted)',
          position: {
            x: 162,
            y: 548,
            width: 700,
            height: 80,
          },
          style: {
            backgroundColor: '#B8D494',
            borderRadius: '0px',
          },
          metadata: {
            confidence: 0.96,
          },
        },
        {
          id: 'layer-15',
          type: 'text',
          content: 'MXN $15,000',
          position: {
            x: 192,
            y: 567,
            width: 182,
            height: 44,
          },
          style: {
            fontSize: '28px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'left',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-16',
          type: 'text',
          content: '8 quincenas',
          position: {
            x: 444,
            y: 567,
            width: 160,
            height: 44,
          },
          style: {
            fontSize: '28px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'center',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-17',
          type: 'text',
          content: 'MXN $2,300',
          position: {
            x: 665,
            y: 567,
            width: 170,
            height: 44,
          },
          style: {
            fontSize: '28px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'left',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-18',
          type: 'shape',
          content: 'White background for third data row',
          position: {
            x: 162,
            y: 636,
            width: 700,
            height: 72,
          },
          style: {
            backgroundColor: '#FFFFFF',
            borderRadius: '0px 0px 8px 8px',
          },
          metadata: {
            confidence: 0.94,
          },
        },
        {
          id: 'layer-19',
          type: 'text',
          content: 'MXN $2,000',
          position: {
            x: 195,
            y: 653,
            width: 167,
            height: 44,
          },
          style: {
            fontSize: '28px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'left',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-20',
          type: 'text',
          content: '8 quincenas',
          position: {
            x: 444,
            y: 653,
            width: 160,
            height: 44,
          },
          style: {
            fontSize: '28px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'center',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-21',
          type: 'text',
          content: 'MXN $3,067',
          position: {
            x: 665,
            y: 653,
            width: 165,
            height: 44,
          },
          style: {
            fontSize: '28px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'left',
            color: '#000000',
          },
          metadata: {
            confidence: 0.99,
            language: 'es',
          },
        },
        {
          id: 'layer-22',
          type: 'shape',
          content: 'Green rounded button background',
          position: {
            x: 329,
            y: 738,
            width: 366,
            height: 58,
          },
          style: {
            backgroundColor: '#B8D494',
            borderRadius: '32px',
            boxShadow: '0px 4px 8px rgba(0,0,0,0.15)',
          },
          metadata: {
            confidence: 0.96,
          },
        },
        {
          id: 'layer-23',
          type: 'text',
          content: 'Depositar en 3 minutos',
          position: {
            x: 371,
            y: 748,
            width: 282,
            height: 38,
          },
          style: {
            fontSize: '24px',
            fontFamily: 'sans-serif',
            fontWeight: '700',
            textAlign: 'center',
            color: '#FFFFFF',
          },
          metadata: {
            confidence: 0.98,
            language: 'es',
          },
        },
        {
          id: 'layer-24',
          type: 'text',
          content: 'Descargo de respainallicita: La aprovaión de solicidad de présamo, el límite de credite recal y el tiempo desembuso del présamo dependen de las palificaciónes individual y los resultos de la "revisión.',
          position: {
            x: 103,
            y: 888,
            width: 818,
            height: 48,
          },
          style: {
            fontSize: '14px',
            fontFamily: 'sans-serif',
            fontWeight: '400',
            lineHeight: '1.4',
            textAlign: 'center',
            color: '#000000',
          },
          metadata: {
            confidence: 0.92,
            language: 'es',
          },
        },
        {
          id: 'layer-25',
          type: 'image',
          content: 'Decorative white sparkle/star icon in bottom right corner',
          position: {
            x: 939,
            y: 943,
            width: 52,
            height: 52,
          },
          style: {
            opacity: '0.8',
          },
          metadata: {
            confidence: 0.93,
            imageType: 'icon',
          },
        },
      ],
    })
  }
  catch (error: any) {
    console.error('[v0] Error analyzing image:', error)
    console.error('[v0] Error details:', error.message)

    return Response.json(
      {
        error: 'Failed to analyze image',
        details: error.message || 'Unknown error',
        layers: [],
      },
      { status: 500 },
    )
  }
}
